package com.quartz.listener;

import com.quartz.jobModel.JobVo;
import com.quartz.jobModel.QuartzJob;
import com.quartz.utils.QuartzScheduleUtil;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;


//调度
@Component
public class QuartzUtilToSaveListener implements ApplicationListener<ContextRefreshedEvent>,QuartzUtilToSaveListenerService{


    @Autowired
    QuartzScheduleUtil quartzUtils;

    Map<String,Object> jobParams =new HashMap<>();

    ContextRefreshedEvent contextRefreshedEvent;


    private  JobVo This_jobVo;


    //开启调度
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        if(This_jobVo!=null){
        try {
                  quartzUtils.addJob(
                          This_jobVo.getJobName(),
                          This_jobVo.getTriggerName(),
                     QuartzJob.class,
                          This_jobVo.getCron(),
                  jobParams,
                  null
                  );
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        }
    }


    @Override
    public void saveJob(JobVo jobVo, Map<String, Object> params) {
        //添加自定义Job任务
        This_jobVo=jobVo;
        jobParams=params;
        this.onApplicationEvent(contextRefreshedEvent);
    }

//    private static String JOB_GROUP_NAME = "FH_JOBGROUP_NAME"; // 任务组
//    private static String TRIGGER_GROUP_NAME = "FH_TRIGGERGROUP_NAME"; // 触发器组

    @Override
    public void removeJob(JobVo jobVo) {
        quartzUtils.removeJob(jobVo.getJobName(),"FH_JOBGROUP_NAME",jobVo.getTriggerName(),"FH_TRIGGERGROUP_NAME");
    }


}
